<?php
include_once('../lib/config.php');
include_once('../lib/Db.class.php');
include_once('../lib/Model.class.php');
include_once('../lib/Snoopy.class.php');
include_once('../lib/Upyun.class.php');
include_once('../lib/function.php');
include_once('/usr/local/xunsearch/sdk/php/lib/XS.php');

// 上传章节到upyun
$GLOBALS['config']['master']['db_database'] = 'gouyg';
$GLOBALS['config']['slave']['db_database']  = 'gouyg';

$redis = new Redis();  
$ret = $redis->connect("localhost","6379");  //php客户端设置的ip及端口
if(!$ret) die('redis connction faild');
$redis->auth(REDIS_PASS);
$redis->select(2);

$basedir = dirname(__FILE__);
$model = new Db;
$upyun = new UpYun(UPYUN_BUCKET_LPN, UPYUN_USER, UPYUN_PASS);
$limit = 100;
$max_mod = 5;
$lock_key = '';

function getMod(&$lock_key) {
    global $redis, $max_mod;
    $mod = 0;
    for ($i=0; $i < $max_mod; $i++) {
        $lock_key = 'upload:'.$mod;
        $lock = $redis->setNx($lock_key, time());
        if(!$lock) {
            $mod++;
            $mod = $mod % $max_mod;
        } else {
            return $mod;
        }
    }

    return false;
}

$mod = getMod($lock_key);
if($mod === false) {
    echo2("$lock_key can't get");
    sleep(2);
    exit();
}

$start_id = (int) $redis->get('start:'.$mod);

while ($limit--) {
    echo2('mod:'.$mod . ', limit:'.$limit.', start_id:'.$start_id);

    if($start_id == 0) {
        $info = $model->find('book_chapter', "remote_file=0 and id%{$max_mod}={$mod} and local_file<>''", "id asc");
    } else {
        $info = $model->find('book_chapter', "remote_file=0 and id%{$max_mod}={$mod} and id>{$start_id}", "id asc");
    }
    
    $filename = $basedir . $info['local_file'];
    if($info && $info['local_file']) {
        $start_id = $info['id'];
        echo2($info['id'] .', '. $info['title'] . ', ' . $filename);

        $upfile = '/book'.$info['local_file'];
        try {
            //判断upyun文件是否已存在
            $upfileinfo = $upyun->getFileInfo($upfile);
            if(!$upfileinfo) {
                throw new Exception("404 Not Find", 405); 
            }

            $r = $model->save('book_chapter', "id='".$info['id']."'", ['remote_file'=>1]);
            if($r) {
                unlink($filename);
                $redis->lPush('BOOK_LOCAL_REMOVE', date('Y-m-d H:i:s').' '.$info['local_file']);
            }
            echo2('upfile_exists, x-upyun-file-size:'.$upfileinfo['x-upyun-file-size']);
        }
        catch(Exception $e) {
            $error = $e->getCode().':'.$e->getMessage();
            try {
                if(!file_exists($filename)) {
                    throw new Exception("Localfile Not Exists", 404); 
                }
                echo2($error.', Start Upload');
            
                $fh = fopen($filename, 'rb');
                $rsp = $upyun->writeFile($upfile, $fh, True); //上传图片，自动创建目录
                fclose($fh);
                if(!$rsp) {
                    //echo2('Upload Failed');
                    throw new Exception("Upload Failed", 406); 
                }

                $r = $model->save('book_chapter', "id='".$info['id']."'", ['remote_file'=>1]);
                if($r) {
                    unlink($filename);
                    $redis->lPush('BOOK_LOCAL_REMOVE', date('Y-m-d H:i:s').' '.$info['local_file']);
                }
                echo2('upfile Upload Success, '.$upfile);
            }
            catch(Exception $e) {
                $error = $e->getCode().':'.$e->getMessage();
                echo2($error.', Upload End');
            }
        } 
    }
    elseif(!$info) {
        echo2('No Upload File');
        sleep(2);
    }
    else {
        echo2('localfile not exists, id:'.$info['id'] . ', ' . $filename);
        sleep(2);
    }
}

$redis->set('start:'.$mod, $start_id);
$redis->delete($lock_key);

